// pages/index/index.js
Page({



  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: "@微信官方，给我2021国庆的国旗渐变头像",
      desc: "领取你的国庆头像，为祖国加油",
      imageUrl: "/static/image/share_img.png",
      path: "/pages/index/index",
      success: function (e) {
        console.log(e);
      },
    };
  },

  onShareTimeline: function () {
    return {
      title: "@微信官方，给我2021国庆的国旗渐变头像",
      desc: "领取你的国庆头像，为祖国加油",
      imageUrl: "/static/image/share_img.png",
      path: "/pages/index/index",
      success: function (e) {
        console.log(e);
      },
    };
  },
  
  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight:0,
    uploadImg: '/static/image/ui/avatar_empty.svg',
    chooseImg: 'frame/guoqing/3.png',
    isIphoneX:false,
    cate: 'hot',
    cates: [
      {
        id: "hot",
        name: "2021新款",
      },
      {
        id: "guoqing",
        name: "渐变国旗",
      },
      {
        id: "zhongqiu",
        name: "清爽国旗",
      },
      {
        id: "zhuangtai",
        name: "其他",
      }
    ],
    chooseImgs:  {
      hot: [ 
        {
          name: "",
          src: "frame/guoqing/1.png",
          type: "frame",
        },
        {
          name: "",
          src: "frame/guoqing/2.png",
          type: "frame",
        },
        {
          name: "",
          src: "frame/guoqing/3.png",
          type: "frame",
        },
        {
          name: "",
          src: "frame/zhongqiu/1.png",
          type: "frame",
        },
      ],
      guoqing: [
        {
          name: "",
          src: "frame/guoqing/1.png",
          type: "frame",
        },
        {
          name: "",
          src: "frame/guoqing/2.png",
          type: "frame",
        },
        {
          name: "",
          src: "frame/guoqing/3.png",
          type: "frame",
        },
        {
          name: "",
          src: "frame/guoqing/4.png",
          type: "frame",
        },
        {
          name: "",
          src: "frame/guoqing/5.png",
          type: "frame",
        },
        {
          name: "",
          src: "frame/guoqing/6.png",
          type: "frame",
        },
      ],
      zhongqiu: [
        {
          name: "",
          src: "frame/zhongqiu/1.png",
          type: "frame",
        },
        {
          name: "",
          src: "frame/zhongqiu/2.png",
          type: "frame",
        },
        {
          name: "",
          src: "frame/zhongqiu/3.png",
          type: "frame",
        },
        {
          name: "",
          src: "frame/zhongqiu/4.png",
          type: "frame",
        },
        {
          name: "",
          src: "frame/zhongqiu/5.png",
          type: "frame",
        },
        {
          name: "",
          src: "frame/zhongqiu/6.png",
          type: "frame",
        },
        {
          name: "",
          src: "frame/zhongqiu/7.png",
          type: "frame",
        },
        {
          name: "",
          src: "frame/zhongqiu/8.png",
          type: "frame",
        },
      ],
      zhuangtai: [
        {
          name: "",
          src: "frame/zhuangtai/1.png",
          type: "frame",
        },
        {
          name: "",
          src: "frame/zhuangtai/2.png",
          type: "frame",
        },
        {
          name: "",
          src: "frame/zhuangtai/3.png",
          type: "frame",
        },
        {
          name: "",
          src: "frame/zhuangtai/4.png",
          type: "frame",
        },
        {
          name: "",
          src: "frame/zhuangtai/5.png",
          type: "frame",
        },
        {
          name: "",
          src: "frame/zhuangtai/6.png",
          type: "frame",
        },
        {
          name: "",
          src: "frame/zhuangtai/7.png",
          type: "frame",
        },
        {
          name: "",
          src: "frame/zhuangtai/8.png",
          type: "frame",
        },
        {
          name: "",
          src: "frame/zhuangtai/9.png",
          type: "frame",
        },
        {
          name: "",
          src: "frame/zhuangtai/10.png",
          type: "frame",
        },
      ],
    }
  },


  // 绘制头像背景
  drawAvatar() {
    let context = wx.createCanvasContext('myAvatar', this);

    context.lineJoin = "round";
    context.lineWidth = 20;
    context.clearRect(0, 0, 200, 200)
    context.drawImage(this.data.uploadImg, 0, 0, 200, 200);
    context.draw(true);
    context.save();
    context.drawImage('/static/image/'+this.data.chooseImg, 0, 0, 200, 200);
    context.draw(true);
    context.save(); 
  },


  // 选择头像图片
  handleUpload() {
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success:res => {
        wx.showToast({
          title: '智能鉴黄中',
          icon: 'success',
          duration: 2000
        })

        setTimeout(() => {
          wx.showLoading({
            title: '鉴定中...',
          })
        
          this.cloudCheck( res.tempFilePaths[0], rs => {
            console.log(rs)
            if (rs) {
              wx.hideLoading()
              this.setData({
                uploadImg: res.tempFilePaths[0]
              }, ()=> {
                this.drawAvatar()
              })
            } else {

              wx.showToast({
                title: '鉴定失败',
                icon: 'error',
                duration: 1000
              })
      
            }
          })
        }, 2000);
      }
    })
  },

  // 保存头像
  handleSaveImg() {
    wx.canvasToTempFilePath({
      canvasId: 'myAvatar',
      success: res => {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success:res => { 
            wx.showToast({
              title: '保存成功'
            })
            setTimeout(() => {
              // 保存跳转
              wx.setStorageSync('uploadImg', this.data.uploadImg)
              wx.setStorageSync('chooseImg', this.data.chooseImg)
              wx.navigateTo({
                url: '/pages/save/save',
              })
            }, 2000);
          },
          fail(res) {
            wx.showToast({
              title: '取消保存...',
              icon: 'none'
            })
          }
        })
      }
    })
  },

  // 切换内容
  handleAvatar(e)
  {
    // console.log(e.target.dataset.avatar)
    this.setData({
      chooseImg: e.target.dataset.avatar
    }, () => {
      this.drawAvatar()
    })
  },


  // 切换登录
  handleLogin(e)
  {
      wx.getUserProfile({
        desc: '用于完善会员资料', 
        success: (res) => { 
            // console.log(res.userInfo.avatarUrl);
            wx.getImageInfo({
              src: res.userInfo.avatarUrl,
              success:  (res)=> {
                // console.log(res.path);
                this.setData({
                  uploadImg: res.path
                }, () => {
                  this.drawAvatar()
                })
              }
            })
        }
      })
  },

  // 切换标题
  handleCate(e)
  {
    // console.log(e.target.dataset.id)
    this.setData({
      cate: e.target.dataset.id
    })
  },
 
  // fix 小程序 底部按钮兼容 iPhone X（解决底部横杠遮挡问题）
  onLoad: function () {
    this.setData({
      "isIphoneX": this.isIphoneX(),
      "statusBarHeight":wx.getSystemInfoSync().statusBarHeight
    })

    this.drawAvatar()
  },

  isIphoneX() {
    let info = wx.getSystemInfoSync();
    if (/iPhone X/i.test(info.model)) {
      return true;
    } else {
      return false;
    }
  },

  cloudCheck(temp, callback) {
    // 图片压缩
    wx.compressImage({
      src: temp,
      quality: 10,
      success: res => {
        console.log(res.tempFilePath)
        
          wx.getFileSystemManager().readFile({
            filePath: res.tempFilePath,
            success: buffer => { 
                wx.cloud.callFunction({
                    name: 'checkImg', //云函数的名称
                    data: {
                        img: buffer.data
                    },
                }).then(res => {
                    console.log(res);
                    if (res.result && res.result.errCode == 87014) {
                        // 发现敏感照片后所做的处理
                      // 下面的imageR是云函数中定义的返回值
                      // return false
                      callback(false)
                    } else {
                        // imageList.push(origin); // 将检查通过的照片添加至imageList，以便其他方法调用
                        // return false
                        callback(true)
                    }
                })
            }
        });
      }
   })
  }
})